package com.legendshop.openportal.sdk.utils.signer;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.digest.HmacAlgorithm;
import com.legendshop.openportal.sdk.model.message.BareContent;

import java.util.Map;
import java.util.TreeMap;

/**
 * hmac256 加签实现
 * @author chan
 */
public class Hmac256ContentSigner implements ContentSigner {


    @Override
    public String buildSign(BareContent bareMessage, String secret) {
        TreeMap<String, Object> map = MapUtil.sort(BeanUtil.beanToMap(bareMessage));
        StringBuffer sb = new StringBuffer();
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            if (null != entry.getKey()
                    && null != entry.getValue()
                    && !"sign".equals(entry.getKey())
                    && !"key".equals(entry.getKey())
            ) {
                sb.append(entry.getKey()).append("=>").append(entry.getValue()).append(";");
            }
        }
        sb.append("key").append("=>").append(secret).append(";");
        String md5 = SecureUtil.md5(sb.toString().toUpperCase()).toUpperCase();
        System.out.println(sb);
        return SecureUtil.hmac(HmacAlgorithm.HmacSHA256, secret).digestHex(md5).toUpperCase();
    }

}
